package hospital.utils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import hospital.common.utils.MD5;
import hospital.model.hosp.Department;
import hospital.model.hosp.Doctor;
import hospital.model.hosp.Schedule;
import hospital.service.DepartmentService;
import hospital.service.DoctorService;
import hospital.service.HospitalService;
import hospital.service.impl.DepartmentServiceImpl;
import hospital.service.impl.DoctorServiceImpl;
import hospital.service.impl.HospitalServiceImpl;
import hospital.service.impl.ScheduleServiceImpl;
import hospital.vo.hosp.DepartmentVo;
import org.apache.commons.lang3.ArrayUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

/**
 * @author ytc
 * @version 1.1
 */
public class IntervalTimeUtil {

    public static final String currentDateStringKey = "currentDateString";
    public static final String validTimeListKey = "validTimeList";
    public static final String currentDayListKey = "currentDayListKey";

    public static final Integer RESERVE_TIME_MAX_COUNT = 3;


    //多少分钟一次
    private static final int reserveIntervalMinutes = 30;//15分钟
    private static final String minuteSplitChar = "~";
    private static final String hourMinuteChar = ":";
    private static final String dateSplitChar = "-";

    //最大为当前时间的，第2天才能预约
    private static final int afterMinDayNum = 1;//从当前天的  第1天开始预约
    private static final int afterMaxDayNum = 15;//从当天的  第10天结束预约
    //只能预约星期一到星期五
    private static int[] validWeekDays =  {
            1,2,3,4,5
    };
    //每天有效的时间段
    private static String[] validIntervalTimePeriods = {
            "09:00-12:00",
            "14:00-17:00"
    };
    //最大60分钟
    private static int maxMinuteNum = 60;
    private static int intTen = 10;

    private static Map<String, Object> resultMap = null;


    /**
     * 自动补0
     * @param i
     * @return
     */
    public static String autoHourFillZero(int i) {
        if(i < intTen) {
            return "0" + i;
        }
        return i + "";
    }
    /**
     *  自动给分钟补0
     * @param i
     * @return
     */
    public static String autoMinuteFillZero(int i) {
        if(i < intTen) {//小于10分钟
            return "0" + i;
        }
        if(i > maxMinuteNum) {//60分钟
            return (i - maxMinuteNum) + "";
        }

        return i + "";
    }

    /*
     * @Author yang
     * @Description //TODO 得到未来的有效分钟
     * @Date 14:50 2023/5/11
     * @Param
     * @return
     **/
    public static List<String> getFutureAllValidMinutes() {
        List<String> validateTimeList = new ArrayList<String>();

        //  多久分钟一次
        int intervalMinute = reserveIntervalMinutes;

        for (String item : validIntervalTimePeriods) {
            String[] s1 = item.split("-");//09:00,12:00

            String minHourMinute = s1[0];//09:00
            String[] ss1 = minHourMinute.split(":");
            int minHour = Integer.valueOf(ss1[0]);//09
            int startMinute = Integer.valueOf(ss1[1]);//00

            String maxHourMinute = s1[1];//12:00
            String[] ss2 = maxHourMinute.split(":");
            int maxHour = Integer.valueOf(ss2[0]);//12
            int endMinute = Integer.valueOf(ss2[1]);//00


            int lastHour = 0;
            int lastMinute = 0;
            StringBuffer sb = new StringBuffer();
            for (int i = minHour; i < maxHour; i++ ) {
                String itemString = "00";
                int startJ = intervalMinute;

                //第一次
                if(i == minHour) {//9 == 9
                    int itemInt = Integer.valueOf(itemString);//00
                    int startInt = Integer.valueOf(startMinute);//13
                    if(startInt > itemInt) {
                        itemString = ss1[1];//13
                    }

                    startJ = startInt + intervalMinute;
                } else {
                    if(lastMinute != (maxMinuteNum-reserveIntervalMinutes)) {
                        String beforehourString = autoHourFillZero(i-1);
                        String curhourString = autoHourFillZero(i);

                        int temp = maxMinuteNum - lastMinute;
                        temp = reserveIntervalMinutes - temp;
                        String curMinuteString = autoHourFillZero(temp);

                        itemString = autoMinuteFillZero(lastMinute);
                        sb.append(beforehourString + hourMinuteChar + lastMinute );//09:00
                        sb.append(minuteSplitChar);//~
                        sb.append(curhourString + hourMinuteChar + curMinuteString);//09:15

                        validateTimeList.add(sb.toString());
                        sb.delete(0, sb.length());//清除数据


                        itemString = curMinuteString;
                        startJ = temp + reserveIntervalMinutes;
                    } else {

                        String beforehourString = autoHourFillZero(i-1);
                        String curhourString = autoHourFillZero(i);

                        int temp = maxMinuteNum - lastMinute;
                        temp = reserveIntervalMinutes - temp;
                        String curMinuteString = autoHourFillZero(temp);

                        itemString = autoMinuteFillZero(lastMinute);
                        sb.append(beforehourString + hourMinuteChar + lastMinute );//09:00
                        sb.append(minuteSplitChar);//~
                        sb.append(curhourString + hourMinuteChar + curMinuteString);//09:15

                        validateTimeList.add(sb.toString());
                        sb.delete(0, sb.length());//清除数据


                        itemString = curMinuteString;
                        startJ = temp + reserveIntervalMinutes;

                    }
                }

                for (int j = startJ; j < maxMinuteNum; j += intervalMinute) {
                    String hourString = autoHourFillZero(i);//09
                    String curMinuteString = autoMinuteFillZero(j);

                    sb.append(hourString + hourMinuteChar + itemString );//09:00
                    sb.append(minuteSplitChar);//~
                    sb.append(hourString + hourMinuteChar + curMinuteString);//09:15


                    validateTimeList.add(sb.toString());
                    sb.delete(0, sb.length());//清除数据

                    itemString = autoMinuteFillZero(j);//15

                    lastMinute = j;//45  记录最后一个分钟数
                }


                lastHour = i;//11  记录最后一个小时数
            }


            //判断最后一个
            //11 < 12 && 60 - 45 >= 15
            //"09:00-12:20"
            int minutesCount = maxMinuteNum - lastMinute + endMinute;//60- 45 + 20 == 35
            if(lastHour < maxHour && minutesCount >= reserveIntervalMinutes) {//11:45~12:20
                int getInt = minutesCount/reserveIntervalMinutes;//2
                int eMinute = 0;
                String endMinuteString = "00";
                String startHour = autoHourFillZero(lastHour);//11:45~12:00
                String lastMinuteString = autoMinuteFillZero(lastMinute);
                String endHourString = autoHourFillZero(1+lastHour);

                //12:15~12:30

                for (int j = 0; j < getInt; j++) {

                    if(j == 0) {
                        if(lastMinute != (maxMinuteNum - reserveIntervalMinutes) ) {
                            int temp = maxMinuteNum - lastMinute;
                            temp = reserveIntervalMinutes - temp;

                            eMinute = temp;
                            endMinuteString = autoHourFillZero(temp);
                        }
                    }

                    sb.append(startHour + hourMinuteChar + lastMinuteString );//16:45
                    sb.append(minuteSplitChar);//~
                    sb.append(endHourString + hourMinuteChar + endMinuteString);//17:00

                    validateTimeList.add(sb.toString());
                    sb.delete(0, sb.length());//清除数据

                    startHour = endHourString;
                    lastMinuteString = endMinuteString;

                    eMinute += reserveIntervalMinutes;//17:15~17:45
                    endMinuteString = autoMinuteFillZero(eMinute);
                }


            }


        }

        return validateTimeList;
    }
    /**
     * 获取预约时间段的结果map
     * @return
     */
    public synchronized static Map<String, Object> getResultMap() {
        if(resultMap == null) {
            resultMap = new HashMap<String, Object>();
        }

        Calendar cal = Calendar.getInstance();
        String nowDate = getNowDate(cal);

        String currentDateString = (String) resultMap.get(currentDateStringKey);
        if(currentDateString == null || "".equals(currentDateString.trim() )) {
            return addNewMapData(nowDate);
        }

        if(nowDate.equals(currentDateString)) {
            return resultMap;
        }

        return addNewMapData(nowDate);
    }
    /**
     * 加载新的map数据
     * @param nowDate
     * @return
     */
    public static Map<String, Object> addNewMapData(String nowDate) {
        resultMap.put(currentDateStringKey, nowDate);

        List<String> dayList = getValidDays();
        resultMap.put(currentDayListKey, dayList);

        List<String> timeList = getFutureAllValidMinutes();

        List<String> validTimeList = getAllValidTime(timeList, dayList);
        resultMap.put(validTimeListKey, validTimeList);

        return resultMap;
    }

    public static void main(String[] args) {


        //new ScheduleServiceImpl().getAllSchedule("1000_1");

        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-dd HH:mm");
        //System.out.println(LocalDateTime.parse("2023-5-12 16:30",formatter).toString());
        //DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime("2023-5-12 16:30");
        //System.out.println(dateTime.toString());
        //System.out.println(new Date());

//        new ScheduleServiceImpl().getSchedule("63e35ee9e7f9cb5702c28f59").toString();
        /*List<String> list = getFutureAllValidMinutes();
        for (String s : list) {
            System.out.println(s);
        }
*/
        /*List<String> list = getValidDays();
        for (String s : list) {
            System.out.println(s);
        }*/
        /*List<String> timeList = getFutureAllValidMinutes();
        List<String> dayList = getValidDays();

        List<String> list = getAllValidTime(timeList, dayList);
        for (String s : list) {
            System.out.println(s);
        }*/
        Map<String, Object> rMap = getResultMap();
        List<String> list = (List<String>) rMap.get(validTimeListKey);
        for (String item : list) {
            System.out.println(item);
        }

    }
    /**
     * 获取日期
     * @param timeList
     * @param dayList
     * @return
     */
    public static List<String> getAllValidTime(List<String> timeList, List<String> dayList) {
        List<String> resultList = new ArrayList<String>();

        StringBuffer sb = new StringBuffer();
        for (String day : dayList) {
            String initDay = day + " ";

            for (String time : timeList) {
                sb.append(initDay);
                sb.append(time);

                resultList.add(sb.toString());

                sb.delete(0, sb.length());
            }

        }

        return resultList;
    }
    /**
     * 获取指定日期合法的预约时间
     * @param
     * @param day
     * @return
     */
    public static List<String> getOneDayValidTime(String day) {
        List<String> timeList = getFutureAllValidMinutes();
        List<String> resultList = new ArrayList<String>();

        StringBuffer sb = new StringBuffer();
        String initDay = day + " ";

        for (String time : timeList) {
            sb.append(initDay);
            sb.append(time);

            resultList.add(sb.toString());

            sb.delete(0, sb.length());
        }


        return resultList;
    }
    /**
     * 获取合法的时间
     * @return
     */
    public static List<String> getValidDays() {
        List<String> validateDayList = new ArrayList<String>();
        for (int i = afterMinDayNum; i <= afterMaxDayNum; i++) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_MONTH, i);

            int weekDay = getChineseWeekDay(cal);

//          int hour = cal.get(Calendar.HOUR);
//          int minute = cal.get(Calendar.MINUTE);
//          int second = cal.get(Calendar.SECOND);


            if(ArrayUtils.contains(validWeekDays, weekDay) ) {//符合要求
                String date = getNowDate(cal);
                validateDayList.add(date);
            }
        }

        return validateDayList;
    }
    /**
     * 获取当前时间 yyyy-MM-dd
     * @param cal
     * @return
     */
    public static String getNowDate(Calendar cal ) {
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);

        return year + dateSplitChar + month + dateSplitChar + day;
    }
    /**
     * 获取中文的星期几
     * @param cal
     * @return
     */
    public static int getChineseWeekDay(Calendar cal) {
        int weekDay = cal.get(Calendar.DAY_OF_WEEK);
        if(weekDay > 1) {
            return weekDay - 1;//星期一到星期六
        } else {
            return 7;//星期日
        }
    }

}
